﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public static class TransformEx {
    public static void SetActive (this Transform transform, bool value) {
        if (transform == null)
            return;
        transform.gameObject.SetActive (value);
    }

    public static T AddComponentEx<T> (this Transform transform) where T : Component {
        T t = transform.GetComponent<T> ();
        if (t != null)
            return t;
        return transform.gameObject.AddComponent<T> ();
    }

    public static void SetScale (this Transform transform, float val) {
        transform.localScale = Vector3.one * val;
    }

    public static void SetTransformFormTarget (this Transform transform, Transform target) {
        if (target == null)
            return;

        transform.position = target.position;
        transform.rotation = target.rotation;
        transform.localScale = target.localScale;
    }

    public static void ResetTransformForLocal (this Transform transform) {
        transform.localPosition = Vector3.zero;
        transform.localRotation = Quaternion.identity;
        transform.localScale = Vector3.one;
    }

    public static void ResetTransform (this Transform transform) {
        transform.position = Vector3.zero;
        transform.rotation = Quaternion.identity;
        transform.localScale = Vector3.one;
    }

    public static Transform FindChildEx (this Transform transform, string ChildName) {
        Transform[] childs = transform.GetComponentsInChildren<Transform> (true);
        foreach (Transform go in childs) {
            if (go.name == ChildName)
                return go;
        }

        return null;
    }

    public static void SetColliderActive<T> (this Transform transform, bool value) where T : Collider {
        Collider col = transform.GetComponent<T> ();
        if (col != null) {
            col.enabled = value;
        }
    }

    public static void SetAllChildActive (this Transform transform, bool value) {
        for (int i = 0; i < transform.childCount; i++) {
            transform.GetChild (i).SetActive (value);
        }
    }

}